let dataDefer = Promise.resolve()

// 读取内容
function readData (name) {
  const fileName = name ? name + '.txt' : 'db.txt'
  return dataDefer = dataDefer.then(() => {
    return new Promise((resolve, reject) => {
      uni.getStorage({
        key: fileName,
        success: function (res) {
          let data = ''
          var result = res?.data
          if(result !== '' && /\{|\[/.test(result)) {
            try {
              let json = JSON.parse(result)
              data = json
            } catch (e) {
              data = result
            }
          }
          resolve({ state: 1, data: data })
        },
        fail (e) {
          resolve({ state: -1, message: e.message, data: '' })
        }
      })
    })
  })
}

// 写入内容
function writeData (data, name) {
  const fileName = name ? name + '.txt' : 'db.txt'
  data = typeof data === 'object' ? JSON.stringify(data, null, '  ') : String(data)
  return dataDefer = dataDefer.then(() => {
    return new Promise((resolve, reject) => {
      uni.setStorage({
        key: fileName,
        data: data,
        success (res) {
          resolve({state: 1, message: '保存数据成功！'})
        },
        fail (e) {
          reject({ state: -1, message: e.message })
        }
      })
    })
  })
}

// 清空内容
function clearData (name) {
  return dataDefer = dataDefer.then(() => {
    return writeData('', name)
  })
}

export default {
  readData,
  writeData,
  clearData
}

export {
  readData,
  writeData,
  clearData
}
